package org.myhibernate.count;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;

import javax.swing.Timer;

import org.myhibernate.cache.CacheContainer;
import org.myhibernate.cache.CacheContainers;
import org.myhibernate.cache.CacheItem;
import org.myhibernate.core.Template;

public class DBCountTimer 
{
	private static Timer timer=null;
	static 
	{
		// 5min
		timer=new Timer(300000, new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{ 
				CacheContainer container=CacheContainers.getCache(DBCount.class);
				Map<Object,CacheItem> map=container.getMap();
				Iterator<Object> iterator=map.keySet().iterator();
				Object key=null;
				DBCount count=null;
				int size=map.size();
				Template<DBCount> template=null;
				if (size>0) {
					template=new Template(DBCount.class);
				}
				try {
					while(iterator.hasNext())
					{
						key=iterator.next();
						count=(DBCount) map.get(key).getObject();
						try {
							template.update(count);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (RuntimeException e1) {
					e1.printStackTrace();
				}
				
				if (template != null) {
					template.close();
				}
			}
		});
		timer.start();
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			@Override
			public void run() {
				timer.stop();
			}
		});
	}
	public static void init(){}
}
